package org.sherlock.ui.gui.components;

import java.awt.BorderLayout;
import java.awt.FlowLayout;
import java.awt.GridLayout;

import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JProgressBar;
import javax.swing.SwingUtilities;

public class JDownloadPanelCenter extends JPanel {
	
	private static final long serialVersionUID = 884379940694060615L;
	private JLabel fileNameLabel;
	private JLabel fileDownloadedLabel;
	private JLabel filePercentageLabel;
	private JProgressBar progressBar;
	private JPanel infoPanel;
	private JPanel textInfoPanel;

	public JDownloadPanelCenter(String fileName, String fileSize, String fileDownloaded, int filePercentage){
		setLayout(new BorderLayout());
		add(getFileNameLabel(fileName),BorderLayout.NORTH);
		add(getInfoPanel(fileSize, fileDownloaded, filePercentage),BorderLayout.CENTER);
	}
	
	private JLabel getFileNameLabel(String fileName){
		if(fileNameLabel==null){
			fileNameLabel=new JLabel(fileName);
		}
		return fileNameLabel;
	}
	
	private JPanel getInfoPanel(String fileSize, String fileDownloaded, int filePercentage){
		if(infoPanel==null){
			infoPanel = new JPanel(new GridLayout(2,1));
			infoPanel.add(getTextInfoPanel(fileSize, fileDownloaded, filePercentage));
			infoPanel.add(getProgressBar(filePercentage));
		}
		return infoPanel;
	}
	
	private JPanel getTextInfoPanel(String fileSize, String fileDownloaded, int filePercentage){
		if(textInfoPanel==null){
			textInfoPanel=new JPanel(new FlowLayout(FlowLayout.LEFT));
			textInfoPanel.add(fileDownloadedLabel = new JLabel(fileDownloaded));
			textInfoPanel.add(new JLabel(" of "));
			textInfoPanel.add(new JLabel(fileSize));
			textInfoPanel.add(filePercentageLabel = new JLabel(" ("+filePercentage+")"));			
		}
		return textInfoPanel;
	}
	
	private JProgressBar getProgressBar(int filePercentage){
		if(progressBar==null){
			progressBar=new JProgressBar();
			progressBar.setMaximum(100);
			progressBar.setMinimum(0);
			progressBar.setValue(filePercentage);
		}
		return progressBar;
	}
	
	public void updateData(final String fileDownloaded, final int filePercentage){
		SwingUtilities.invokeLater(new Runnable() {
			
			@Override
			public void run() {
				fileDownloadedLabel.setText(fileDownloaded);
				filePercentageLabel.setText(" ("+filePercentage+")");
				progressBar.setValue(filePercentage);
			}
		});
	}

}
